package beans.xml;

import java.io.StringReader;
import java.io.StringWriter;
import java.util.List;
import java.util.Map;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

public class XMLWithBean
{
	public static void main(String[] args)
	{
//		User user = new User();
//		user.setId(10001L);
//		user.setName("demo");
//
//		Map<String, String> maps = Maps.newHashMap();
//		maps.put("11", "111");
//		maps.put("12", "111");
//		maps.put("13", "111");
//		user.setHouses(maps);
//
//		user.setPassword("111111");
//
//		List<String> lists = Lists.newArrayList();
//		lists.add("22");
//		lists.add("23");
//		lists.add("24");
//		lists.add("25");
//		user.setInterests(lists);
//
//		System.out.println(xml(user));
//		System.out.println(bean(xml(user), user).toString());
	}

	public static String xml(Object obj)
	{
		StringWriter writer = new StringWriter();

		try
		{
			JAXBContext jaxbContext = JAXBContext.newInstance(obj.getClass());
			Marshaller marshaller = jaxbContext.createMarshaller();
			marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
			marshaller.setProperty(Marshaller.JAXB_ENCODING, "GBK");
			// 设置输入XML是否有“<?xmlversion="1.0"encoding="UTF-8"standalone="yes"?>”
			marshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.FALSE);
			marshaller.marshal(obj, writer);
		}
		catch (Exception e)
		{
		}
		return writer.getBuffer().toString();

	}

	@SuppressWarnings("unchecked")
	public static <T> T bean(String objXML, T obj)
	{
		try
		{
			JAXBContext jaxbContext = JAXBContext.newInstance(obj.getClass());
			Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
			obj = (T) unmarshaller.unmarshal(new StringReader(objXML));
		}
		catch (Exception e)
		{
		}
		return obj;
	}
}
